<?php
namespace Wechat\Controller;
use Think\Controller;
class CommonController extends Controller {
    
        protected $userModel;

        protected $returnData;

        public function _initialize(){
            
            $this->userModel = D('user');
            
            $this->returnData['errorCode'] = 200;
            $this->returnData['errorMsg'] = '';
//
//            //授权微信
//            //检查是否为pc
//            if (check_wap()) {
//                //是否是在为微信的内嵌浏览器中打开
//                if (is_weixin()) {
////                    if (empty($userInfo) || !isset($userInfo)) {
////                        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . C('appid') . '&redirect_uri=http://' . $_SERVER['HTTP_HOST'] . '/Wechat/Api/auth3/&response_type=code&scope=snsapi_userinfo&state=' . urlencode(get_url()) . '&connect_redirect=1#wechat_redirect';
////                        header('Location: ' . $url);
////                        exit();
////                    }
//                } else {
//                    //header("Location: http://www.baidu.com/");
//                    //exit();
//                }
//            } else {
//                //header("Location: http://www.baidu.com/");
//                //exit();
//            }
//
//            //获取jsapi_ticket
//            $this -> assign('jsapi_ticket',jsapi_ticket());

        }  

        public function checkIsSameUser($uid) {
            
            $openid = I('cookie.openid');
            
            $map['openid'] = $openid;
            
            $user = $this->userModel->where($map)->find();
            
            return $uid == $user['uid'];
            
        }
        
        public function sendMobileCode() {
            
            $mobile = I('post.mobile');
            
            $num = rand(1000,9999);
            
            newmms($mobile, "验证码为：".$num."请在10分钟之内输入");
            
            session('mms',$num);
            
            session('mobile',$mobile);
            
            echo json_encode($this->returnData);
            
        }
        
        function uploadImage() {
            
            $xmlstr =  $GLOBALS['HTTP_RAW_POST_DATA'];
            if(empty($xmlstr)) 
                $xmlstr = file_get_contents('php://input');
            
            $arr = explode('&', $xmlstr);
            
            $fileStreamStr = $arr[0];
            
            $fileStreamArr = explode('=', $fileStreamStr);
            
            $fileStream = base64_decode(rawurldecode($fileStreamArr[1]));
            
            $targetFolder = '/Uploads/'; // Relative to the root

            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            
            $filename = md5(time()) . '.jpg';//要生成的图片名字

            $targetFile = rtrim($targetPath,'/') . '/' . $filename;
            
            $image = $fileStream;//得到post过来的二进制原始数据
            $file = fopen($targetPath.$filename,"w");//打开文件准备写入
            fwrite($file,$image);//写入
            fclose($file);//关闭
 
            $imgUrl = '.'.$targetFolder.$filename;

            $thinkImage = new \Think\Image(); 
            $thinkImage->open($imgUrl);

            $imagePath = '.'.$targetFolder . 'thumb_' . $filename;

            $thinkImage->thumb(300,300,\Think\Image::IMAGE_THUMB_CENTER)->save($imagePath);
            
            $this->returnData['data'] = C('rooturl') . $targetFolder . 'thumb_' . $filename;
            
            echo json_encode($this->returnData);
            
        }
        
        public function getCurrentTime() {
            return date('Y-m-d H:i:s');
        }
        
        public function calculateSecondGap($from, $to) {
            $min=ceil(strtotime($to)-strtotime($from));
            return $min;
        }
        
        public function calculateMinGap($from, $to) {
            $min=ceil($to-$from)/60;
            return $min;
        }
        
        /** 
        * @desc 根据两点间的经纬度计算距离 
        * @param float $lat 纬度值 
        * @param float $lng 经度值 
        */
        function getDistance($lat1, $lng1, $lat2, $lng2) { 
            
            $earthRadius = 6367000; //approximate radius of earth in meters 

            /* 
            Convert these degrees to radians 
            to work with the formula 
            */

            $lat1 = ($lat1 * pi() ) / 180; 
            $lng1 = ($lng1 * pi() ) / 180; 

            $lat2 = ($lat2 * pi() ) / 180; 
            $lng2 = ($lng2 * pi() ) / 180; 

            /* 
            Using the 
            Haversine formula 

            http://en.wikipedia.org/wiki/Haversine_formula 

            calculate the distance 
            */

            $calcLongitude = $lng2 - $lng1; 
            $calcLatitude = $lat2 - $lat1; 
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
            $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
            $calculatedDistance = $earthRadius * $stepTwo; 

            return round($calculatedDistance);  //这个计算结果单位是M
        } 
  
	public function guid() {
            
            if (function_exists('com_create_guid'))
            {
                    return com_create_guid();
            }
            else
            {
                    mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
                    $charid = strtoupper(md5(uniqid(rand(), true)));
                    $hyphen = chr(45);// "-"
                    $uuid = //chr(123)// "{"
                    substr($charid, 0, 8).$hyphen
                    .substr($charid, 8, 4).$hyphen
                    .substr($charid,12, 4).$hyphen
                    .substr($charid,16, 4).$hyphen
                    .substr($charid,20,12);
                    //.chr(125);// "}"
                    return $uuid;
            }
	}

    public function sendMobileContentByMobile($mobile, $content) {

        mms(C('mmskey'), $mobile, $content);

    }
        
}